import React, { Component } from 'react'

import FilterTitle from '../FilterTitle'
import FilterPicker from '../FilterPicker'
import FilterMore from '../FilterMore'

import styles from './index.module.css'

import { getFilter } from '../../../../api/filter'

/**
 * 标题高亮状态
 */
const titleSelectedStatus = {
  area: false,
  mode: false,
  price: false,
  more: false
}
// 默认选中的状态
const selectedValues = {
  area: ["area", null],
  mode: ["null"],
  price: ["null"],
  more: []
};
export default class Filter extends Component {

  state = {
    titleSelectedStatus,
    // 控制 FilterPicker 或 FilterMore 组件的展示或隐藏
    openType: '',
    // 筛选条件数据
    filterData: {},
    // 默认选中的状态
    selectedValues,
  }
  componentDidMount() {
    this.getFilterData()
  }



  // 封装renderFilterMore方法，渲染FilterMore组件
  renderFilterMore() {
    const {
      openType,
      filterData: { roomType, oriented, floor, characteristic }
    } = this.state;
    const { more } = this.state.selectedValues
    // 把数据封装到一个对象中，方便传递
    const data = {
      roomType,
      oriented,
      floor,
      characteristic
    };
    if (openType !== "more") {
      return null;
    }
    // 传递给子组件
    return <FilterMore data={data} type="more" onSave={this.onSave} onCancle={this.onCancle} defaultValue={more} />;
  }

  // 渲染FilterPicker组件的方法
  renderFilterPicker() {
    let data = []
    let col = 1
    const { openType, filterData: { area, subway, price, rentType } } = this.state
    const value = this.state.selectedValues[openType]
    switch (openType) {
      case 'area':
        data = [area, subway]
        col = 3
        break;
      case 'mode':
        data = rentType

        break;
      case 'price':
        data = price
        break;
      default:
        return null
    }

    return <FilterPicker key={openType} onCancle={this.onCancle} onSave={this.onSave} province={data} col={col} type={openType} value={value} />
  }

  // 获取筛选数据
  async getFilterData() {
    const { value } = JSON.parse(window.localStorage.getItem('liu_city'))
    const { data } = await getFilter(value);
    this.setState({
      filterData: data.body
    })
  }

  // 确定（隐藏对话框）
  onSave = (type, value) => {
    const { titleSelectedStatus } = this.state
    // 创建新的标题选中状态对象
    const newTitleSelectedStatus = { ...titleSelectedStatus }

    // 菜单高亮逻辑处理
    const selectedVal = value
    if (
      type === 'area' &&
      (selectedVal.length !== 2 || selectedVal[0] !== 'area')
    ) {
      // 高亮
      newTitleSelectedStatus[type] = true
    } else if (type === 'mode' && selectedVal[0] !== 'null') {
      // 高亮
      newTitleSelectedStatus[type] = true
    } else if (type === 'price' && selectedVal[0] !== 'null') {
      // 高亮
      newTitleSelectedStatus[type] = true
    } else if (type === 'more' && selectedVal.length !== 0) {
      // 更多选择项 FilterMore 组件
      newTitleSelectedStatus[type] = true
    } else {
      newTitleSelectedStatus[type] = false
    }

    /* 
      组装筛选条件：

      1 在 Filter 组件的 onSave 方法中，根据最新 selectedValues 组装筛选条件数据 filters。
      2 获取区域数据的参数名：area 或 subway（选中值数组的第一个元素）。
      3 获取区域数据的值（以最后一个 value 为准）。
      4 获取方式和租金的值（选中值的第一个元素）。
      5 获取筛选（more）的值（将选中值数组转化为以逗号分隔的字符串）。

      {
        area: 'AREA|67fad918-f2f8-59df', // 或 subway: '...'
        mode: 'true', // 或 'null'
        price: 'PRICE|2000',
        more: 'ORIEN|80795f1a-e32f-feb9,ROOM|d4a692e4-a177-37fd'
      }
    */

    const newSelectedValues = {
      ...this.state.selectedValues,
      // 只更新当前 type 对应的选中值
      [type]: value
    }

    const { area, mode, price, more } = newSelectedValues

    // 筛选条件数据
    const filters = {}

    // 区域
    const areaKey = area[0]
    let areaValue = 'null'
    if (area.length === 3) {
      areaValue = area[2] !== 'null' ? area[2] : area[1]
    }
    filters[areaKey] = areaValue

    // 方式和租金
    filters.mode = mode[0]
    filters.price = price[0]

    // 更多筛选条件 more
    filters.more = more.join(',')

    // console.log(filters)

    // 调用父组件中的方法，来将筛选数据传递给父组件
    this.props.onFilter(filters)

    // 隐藏对话框
    this.setState({
      openType: '',

      // 更新菜单高亮状态数据
      titleSelectedStatus: newTitleSelectedStatus,

      selectedValues: newSelectedValues
    })
  }

  // 关闭弹层
  onCancle = (type) => {
    const { titleSelectedStatus, selectedValues } = this.state;
    let newTitleSelectedStatus = { ...titleSelectedStatus };
    let selectedVal = selectedValues[type];
    if (
      type === "area" &&
      (selectedVal.length !== 2 || selectedVal[0] !== "area")
    ) {
      newTitleSelectedStatus[type] = true;
    } else if (type === "mode" && selectedVal[0] !== "null") {
      newTitleSelectedStatus[type] = true;
    } else if (type === "price" && selectedVal[0] !== "null") {
      newTitleSelectedStatus[type] = true;
    } else if (type === "more" && selectedVal.length !== 0) {
      // 更多选择
      newTitleSelectedStatus[type] = true;
    } else {
      newTitleSelectedStatus[type] = false;
    }
    // 隐藏对话框
    this.setState({
      openType: "",
      titleSelectedStatus: newTitleSelectedStatus
    });
  }

  // 点击事件
  myClick = type => {
    return () => {
      const { titleSelectedStatus, selectedValues } = this.state
      let newTitleSelectedStatus = { ...titleSelectedStatus }


      Object.keys(titleSelectedStatus).forEach(key => {
        if (key === type) {
          newTitleSelectedStatus[type] = true;
          return
        }
        // 其他标题
        let selectedVal = selectedValues[key];
        if (
          key === 'area' &&
          (selectedVal.length !== 2 || selectedVal[0] !== 'area')
        ) {
          newTitleSelectedStatus[key] = true;
        }
        else if (key === "mode" && selectedVal[0] !== "null") {
          newTitleSelectedStatus[key] = true;
        } else if (key === "price" && selectedVal[0] !== "null") {
          newTitleSelectedStatus[key] = true;
        } else if (key === "more" && (selectedVal.length > 0)) {
          // 更多选择
          newTitleSelectedStatus[key] = true;
        } else {
          newTitleSelectedStatus[key] = false;
        }
      })

      this.setState(params => {
        return {
          titleSelectedStatus: newTitleSelectedStatus,
          openType: type
        }
      })
    }
  }

  render() {
    return (
      <div className={styles.root} >
        {/* 前三个菜单的遮罩层 */}
        {/* <div className={styles.mask} /> */}

        <div className={styles.content} >
          {/* 标题栏 */}
          <FilterTitle
            titleSelectedStatus={this.state.titleSelectedStatus}
            myClick={this.myClick}
          />

          {/* 前三个菜单对应的内容： */}
          {this.renderFilterPicker()
          }

          {/* 最后一个菜单对应的内容： */}
          {/* <FilterMore /> */}
          {this.renderFilterMore()}
        </div>
      </div>
    )
  }
}
